<template>
	<view>
		<div class="back_bar flex-v-center pad-lr20 h90">
			<div @click="backToMaterial" class="w100 back_icon flex">
				<i class="icon-arrow-left mar-20 fs24"></i>
				<span> 返回 </span>
			</div>
			<div class="flex-1 fw-bold flex-center"> 编辑文章 </div>
			<div class="w100"></div>
		</div>
		<div class="art_base_info">
			<div class="info">
				<div @click="editTitle">{{artDetail.title}}</div>
				<!-- <p>{{artDetail.subDes}}</p> -->
			</div>
			<div class="img">
				<pub-upload-img v-model="artDetail.pictureUrl"></pub-upload-img>	
				<!-- <image :src="artDetail.pictureUrl" mode="" /> -->
			</div>
		</div>
		<div class="banner_img_list" v-if="artDetail.imgUrls && artDetail.imgUrls.length">
			<pub-upload-img width="160rpx" height="160rpx" v-model="artDetail.imgUrls" :limit="99"></pub-upload-img>
		</div>
		<div class="empty_add flex-column flex-center mar-b10" @click.self="clearActEl">
			<addContent ref="addContent" @active="addContentType" :editText="false"></addContent>
		</div>
		<div class="art_ad_container" ref="artAdcontainer">
			<div class="rich-context" id="content_container_bbd" ref="artContext"></div>
			<div class="ad_list">
				<div class="art_ad_item" v-for="(item, index) in advertList" :key="index" :style="{top: item.posY + 'px'}">
					<adItem :id="item.id"></adItem>
				</div>
			</div>
		</div>

		<div v-if="actEl" 
			class="edit_alert" 
			:data-offsetTop="actEl.offsetTop" 
			:data-offsetHeight="actEl.offsetHeight" 
			:data-containerOffsetTop="$refs.artAdcontainer.offsetTop" 
			:style="{top: actEl && ($refs.artAdcontainer.offsetTop + actEl.offsetTop + actEl.offsetHeight) + 'px'}">
			<div class="line">
				<p @click="insertAfter('txt')"> <i class="icon-plus"></i> 文字</p>
				<p @click="insertAfter('img')"> <i class="icon-plus"></i> 图片</p>
				<p @click="insertAfter('video')"> <i class="icon-plus"></i> 视频</p>
			</div>
			<div class="line">
				<p @click="insertAfter('advert')"> <i class="icon-plus"></i> 广告 </p>
				<p @click="deleteItem"> <i class="icon-minus"></i> 删除 </p>
				<p v-if="actELType == 'txt'" @click="editItem"> <i class="icon-edit"></i> 修改 </p>
			</div>
			<!-- <span class="mar-r20" @click="deleteItem">删除</span>
			<span class="mar-r20">修改</span>
			<span class="mar-r20" @click="insertAfter">新增</span>
			<span class="mar-r20" @click="clearActEl">close</span> -->
		</div>

		<div class="edit_container" v-if="editContext.visible">
			<div class="edit_context" contenteditable="true" ref="editContent"></div>
			<div class="btns">
				<div class="button" @click="confirmEditContext('cancel')">取消</div>
				<div class="button" @click="confirmEditContext('confirm')">确定</div>
			</div>
		</div>

		<div class="bottom_btns">
			<template v-if="$store.getters.isSuperManger">
				<div class="delete_art" @click="deleteMaterial">删除文章</div>
				<div @click="updateMaterial" class="save_material">
					<p>保存</p>
					<span>更到新素材库</span>
				</div>
			</template>
			<div class="cancel_art_del" @click="cancelDelete">撤销</div>
			<div class="save_art" @click="saveSubmit">保存</div>
		</div>
		<pub-text-editer ref="textEditer"></pub-text-editer>
	</view>
</template>

<script>
import addContent from '@/components/pages/addContent'
import { getDynamicInfo, editDynamic } from '@/request/art'
import adItem from '@/components/pages/adItem'
import { sysDeleArt } from '@/request/sys'
export default {
	components: {
        addContent,
		adItem
    },
	data() {
		return {
			from: '', //myMaterial
			dynamicId: '',
			artDetail: {},
			editContext: {
				visible: false,
				type: '', //modify:修改文本，insert: 插入文本
				nodeType: '' , //text img video
				imgSrc: '',
				videoSrc: '',
				advertStr: ''
			},
			deleteElList: [],
			actEl: null,
			actELType: 'txt',
			advertList: []
		}
	},
	onLoad(options) {
		if(options.id) this.dynamicId = options.id;
		if(options.from) this.from = options.from;
		if(this.$store.state.user.userInfo.vip != '01') {
			return this.$interact.modal({
				title: '提示',
				content: '您不是会员，无权编辑文章',
				confirmText: '立即开通会员',
				showCancel: true,
			}).then(action => {
				if(action.confirm) {
					this.$navigate.toVip()
				} else{
					this.$navigate.to('/pages/material')
				}
			})
		}
		this.getArtDetail()
	},
	methods: {
		backToMaterial() {
			// 被刷新后，历史记录不存在了，需要返回到首页
			let prePageFullPath = this.$prePage() && this.$prePage().__page__.fullPath || ''
			if (!prePageFullPath) {
				return this.$navigate.redirect('/pages/material/detail?id=' + this.dynamicId)
			}			
			this.$navigate.back()
		},
		getArtDetail() {
			getDynamicInfo({
				dynamicId: this.dynamicId
			}).then(res => {
				let detail = res.data.dynamic
				detail.subDes = detail.context.replace(/(<.*?>)/ig, '')
				detail.subDes = detail.subDes.replace(/(\&[a-zA-Z]*\;)/ig, '')

				//小红书 文章为纯文本文章，里面只有<br>换行符和 html,body,head这几个标签。要全部给裹一层p标签才能编辑
				if(detail.originType == '05') { 
					let xhsContent = detail.context
					xhsContent = xhsContent.replace(/<((\/?html)|(\/?head)|(\/?body))>/ig, '')
					xhsContent = xhsContent.replace(/<br>/ig, '>|<')
					xhsContent = xhsContent.replace(/<p><\/p>/ig, '')
					xhsContent = xhsContent.replace(/\n/ig, '')
					let conArr = xhsContent.split('>|<')
					console.log(conArr);
					if(conArr.length > 1) {
						detail.context = conArr.reduce((s, i) => {
							return s + `<p>${i.trim()}</p>`
						}, '')
					} else {
						let context = conArr[0].trim()
						console.log(context);
						if(context.slice(0, 1) != '<') {
							detail.context = `<div>${context}</div>`
						}
					}
				}
				this.artDetail = detail
				console.log(this.artDetail);

				this.$nextTick(() => {
					this.$refs.artContext.innerHTML = res.data.dynamic.context
					this.formatAdvert()
					this.$refs.artContext.addEventListener('click', e => {

						if(this.actEl) {
							this.actEl.setAttribute('class', this.actEl.className.replace(' act_edit_node', ''))
							this.actEl = null;
						}

						let actEl = e.target
						console.dir(e.target);	
						if(actEl.id == 'content_container_bbd') return
						if(actEl.tagName == 'IMG') {
							this.actELType = 'img'
						} else if(actEl.tagName == 'VIDEO') {
							this.actELType = 'video'
						} else {
							if(actEl.id.indexOf('rich_advert_') > -1) {
								this.actELType = 'advert'
							} else {
								this.actELType = 'txt'
							}
						}
						this.actEl = actEl
						actEl.setAttribute('class', actEl.className + ' act_edit_node')
					})
				})
			})
		},
		// 删除
		deleteItem() {
			let deleteElPlaceholderNode = document.createElement('div')
			deleteElPlaceholderNode.setAttribute('id', 'deled_' + (this.deleteElList.length + 1))

			let parentEl = this.actEl.parentNode
			parentEl.insertBefore(deleteElPlaceholderNode, this.actEl)

			let classStr = this.actEl.getAttribute('class')
			classStr = classStr.replace('act_edit_node', '')
			this.actEl.setAttribute('class', classStr)

			this.deleteElList.push(this.actEl.outerHTML)
			parentEl.removeChild(this.actEl)
			this.clearActEl()
			this.formatAdvert()
		},
		// 撤销删除
		cancelDelete() {
			if(!this.deleteElList.length) return this.$interact.toast('暂无可撤销删除')
			let parentElHTML = this.$refs.artContext.innerHTML
			let placeholder = `<div id="deled_${this.deleteElList.length}"></div>`
			let reg = new RegExp(placeholder, 'g')
			parentElHTML = parentElHTML.replace(reg, this.deleteElList[this.deleteElList.length - 1])
			this.$refs.artContext.innerHTML = parentElHTML
			this.deleteElList.splice(this.deleteElList.length-1, 1)
			this.formatAdvert()
		},
		// 修改
		editItem() {
			this.editContext.visible = true
			this.editContext.type = 'modify'
			this.$nextTick(() => {
				this.$refs.editContent.innerHTML = this.actEl.innerHTML
			})
		},
		// 文章中部插入文字、图片、视频（插入图片视频调用addContent组件，并出发addContent的回调）
		insertAfter(nodeType) {
			if(nodeType == 'txt') {
				this.editContext.type = 'insert'
				this.editContext.visible = true
				this.editContext.nodeType = nodeType
			} else {
				// 这里调佣addContent里的方法，操作会执行 addContentType方法
				this.$refs.addContent.activeFn(nodeType)
			}
		},
		// 文章最顶端添加文字/图片/视频
		addContentType(e) {
			// this.actEl = null;
			if(e.type == 'txt') {
				this.insertAfter(e.type)
			} else {
				if(e.type == 'img'){
					this.editContext.imgSrc = e.content
				} else if(e.type == 'video'){
					this.editContext.videoSrc = e.content
				} else if(e.type == 'advert') {
					this.editContext.advertStr = e.content
				}
				this.editContext.type = 'insert'
				this.editContext.nodeType = e.type
				this.confirmEditContext('confirm')
			}
		},
		// 确定插入的 DOM操作
		confirmEditContext(type) {
			if(type == 'confirm') {
				if(this.editContext.type == 'modify') {
					this.actEl.innerHTML = this.$refs.editContent.innerHTML
					this.$refs.editContent.innerHTML = ''
				} else if(this.editContext.type == 'insert') {
					let newNode = null;
					if(this.editContext.nodeType == 'txt') {
						newNode = document.createElement("div");
						newNode.innerHTML = this.$refs.editContent.innerHTML
					} else if(this.editContext.nodeType == 'img') {
						newNode = document.createElement("img");
						newNode.src = this.editContext.imgSrc
					} else if(this.editContext.nodeType == 'video') {
						newNode = document.createElement("video");
						newNode.src = this.editContext.videoSrc
					} else if(this.editContext.nodeType == 'advert') {
						newNode = document.createElement("div");
						newNode.setAttribute("id", 'rich_advert_' + this.editContext.advertStr + '_temp_' + Math.random().toString(32).slice(2) + '_')
						newNode.setAttribute("class", 'rich_advert_item')
					}
					
					let parentEl = null;
					if(this.actEl) {
						parentEl = this.actEl.parentNode
						parentEl.insertBefore(newNode, this.actEl.nextElementSibling)
					} else {
						let parentEl = this.$refs.artContext
						parentEl.insertBefore(newNode, parentEl.firstChild)
					}
				}
				this.clearActEl()
			}
			this.formatAdvert()
			this.editContext.visible = false
		},

		formatAdvert() {
			setTimeout(() => {
				this.$nextTick(() => {
					let artStr = this.$refs.artContext.innerHTML
					let adReg = /id="rich_advert_(\d+)(_temp_.*?_)"/ig
					let advertList = []
					var res = null
					while(res = adReg.exec(artStr)) {
						advertList.push({
							id: res[1],
							posY: document.getElementById('rich_advert_' + res[1] + res[2]).offsetTop
						})
					}
					this.advertList = advertList
				})
			}, 0)
		},
		
		editTitle() {
            this.$refs.textEditer.open({
                content: this.artDetail.title,
            }).then(rst => {
                this.artDetail.title = rst
            })
        },

		clearActEl() {
			if(this.actEl) {
				this.actEl.setAttribute('class', this.actEl.className.replace(' act_edit_node', ''))
			}
			this.actEl = null
		},
		saveSubmit(onlyEdit) {
			let data = {
				dynamicId: this.dynamicId,
				pictureUrl: this.artDetail.pictureUrl,
				title: this.artDetail.title,
			}
			// context: this.$refs.artContext.innerHTML,
			let context = this.$refs.artContext.innerHTML
			context = context.replace(/<div.*?id=\"deled_\d+\"><\/div>/ig, '')
			context = context.replace(/act_edit_node/ig, '')
			data.context = context

			if(this.artDetail.imgUrls && this.artDetail.imgUrls.length) {
				let imgsStrs = this.artDetail.imgUrls.reduce((s, i) => {
					return s +  `<img data-type='afteradd' src='${i}'/>`
				}, '')
				data.context += imgsStrs
			}

			if(onlyEdit == '01') {
				data.onlyEdit = '01'
			}
			
			if(!data.title) return this.$interact.toast('标题不能为空')
			if(!data.pictureUrl) return this.$interact.toast('主图不能为空')
			if(!data.context) return this.$interact.toast('文章内容不能为空')
			console.log(data);
			editDynamic(data).then(res => {
				this.$interact.modal(res.msg).then(() => {
					if(onlyEdit == '01') {
						this.backToMaterial()
					} else {
						if(res.data && res.data.dynamicId) {
							this.$navigate.to('/pages/material/detail?form=pubMaterialEditSuccess&id=' + res.data.dynamicId)
						} else {
							this.backToMaterial()
						}
					}
				})
			})
		},
		deleteMaterial(){ 
			this.$interact.modal({
                title: '提示',
                content: '是否删除该文章？',
                showCancel: true
            }).then(action => {
				if(action.confirm) {
					sysDeleArt({
						id: this.dynamicId
					}).then(res => {
						this.$interact.modal(res.msg).then(() => {
							if(this.from == 'myMaterial') {
								this.$navigate.to('/pages/user/myMaterial')
							} else {
								this.$navigate.to('/pages/material')
							}
						})
					})
				}
            })
		},
		updateMaterial() {
			this.$interact.modal({
                title: '提示',
                content: '是否更新至素材库',
                showCancel: true
            }).then(action => {
				if(action.confirm) {
					this.saveSubmit('01')
				}
            })
		},
	}
}
</script>

<style lang="less" scoped>
.back_bar{
	background: #fff;
	border-bottom: 1px solid #ddd;
	position: sticky;
	top: 0;
}
.art_base_info{
	width: 100%;
	display: flex;
	padding: 20rpx;
	background: #fff;
	margin-bottom: 20rpx;
	align-items: center;
	.info{
		width: 1px;
		flex: 1;
		max-height: 180rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		// align-items: center;
		>div{
			width: 100%;
			font-weight: bold;
			.overflow(3);
		}
		p{
			width: 100%;
			font-size: 26rpx;
			color: #999;
			.overflow(2);
		}
	}
	.img{
		width: 200rpx;
		height: 180rpx;
		margin-left: 20rpx;
		flex-shrink: 0;
		image{
			border-radius: 10rpx;
			width: 100%;
			height: 100%;
		}
	}
	
}
.banner_img_list{
	background: #fff;
	padding: 20rpx 0 20rpx 25rpx;
}

.art_ad_container{
	background: #fff;
	position: relative;
	.rich-context{
		padding: 0 30rpx 20rpx;
		padding-bottom: 350rpx;
	}
	.ad_list{
		.art_ad_item{
			position: absolute;
			left: 30rpx;
			width: 690rpx;
			height: 320rpx;
			padding: 10rpx 0;
			z-index: 1;
		}
	}
}

.edit_container{
	width: 100%;
	height: 100vh;
	position: fixed;
	top: 0;
	left: 0;
	background: #fff;
	z-index: 30;
	padding: 30rpx;
	.edit_context{
		width: 100%;
		min-height: 500rpx;
		padding: 10rpx;
		border-radius: 20rpx;
		border: 1px solid @mainColor;
	}
	.btns{
		display: flex;
		align-items: center;
		justify-content: space-between;
		.button{
			width: 320rpx;
			height: 80rpx;
			background: @mainColor;
			border-radius: 10rpx;
			text-align: center;
			line-height: 80rpx;
			margin: 20rpx auto;
			color: #fff;
			&:first-child{
				background: #f2f2f2;
				color: #333;
			}
		}
	}
}
.edit_alert{
	width: 600rpx;
	left: 50%;
	position: absolute;
	margin-left: -300rpx;
	border-radius: 10rpx;
	background: #fff;
	box-shadow: 0 0 10rpx #999;
	padding: 10rpx;
	z-index: 10;
	.line{
		display: flex;
		border-bottom: 1px solid #ddd;
		&:first-child{
			padding-bottom: 10rpx;
		}
		&:last-child{
			margin-top: 10rpx;
			border-bottom: 0;
			// p{
			// 	border-right: 1rpx solid #ddd;
			// 	&:last-child{
			// 		border-right: 0;
			// 	}
			// }
		}
		p{
			height: 70rpx;
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			i{
				font-size: 20rpx;
				margin-right: 10rpx;
				height: 32rpx;
				width: 32rpx;
				line-height: 32rpx;
				border: 1rpx solid #375ec1;
				color: #375ec1;
				.align(center);
				border-radius: 50%;
			}
		}
	}	
}

.bottom_btns{
	width: 100%;
	height: 100rpx;
	position: fixed;
	bottom: 0;
	left: 0;
	display: flex;
	background: #fff;
	border-top: 1px solid #ddd;
	z-index: 5555;
	
	div{
		flex: 1;
		.align(center);
		font-size: 34rpx;
		
	}
	.save_art{
		background: @mainColor;
		color: #fff;
	}
	.delete_art{
		flex: none;
		width: 180rpx;
		background: #CE3E27;
		color: #fff;
		font-size: 26rpx;
	}
	.save_material{
		flex: none;
		width: 180rpx;
		background-color: #1c97e9;
		color: #fff;
		font-size: 26rpx;
	}
}
</style>
